﻿using System;
using System.Collections.Generic;
using Vote.Database.DataAccess;

namespace Vote.Business
{
    /// <summary>
    /// 用户投票逻辑
    /// </summary>
    public class UserVoteModel
    {
        #region 单例
        private static UserVoteModel _Instance = new UserVoteModel();
        public static UserVoteModel Instance { get { return _Instance; } }
        #endregion

        /// <summary>
        /// 获取用户投票状态
        /// </summary>
        /// <param name="actionId">活动id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public Tuple<int, ActionEntity> GetUserVoteStatus(int actionId, string userId)
        {
            //默认进行中
            int voteStatus = 1;
            DateTime configTime = DateTime.MinValue;
            UserActionAccess access = new UserActionAccess();

            // 投票时间未到
            var actionconfig = access.GetActionInfo(actionId);

            // 不存在该活动
            if (actionconfig == null) { return null; }

            var actionInfo = new ActionEntity()
            {
                ActionID = actionconfig.ID,
                ActionName = actionconfig.ActionName,
                ActionDesc = actionconfig.ActionDesc,
                BeginTime = actionconfig.BeginTime,
                CreatTime = actionconfig.CreateTime,
                EndTime = actionconfig.EndTime,
            };


            if (actionInfo.BeginTime > DateTime.Now)
            {
                //活动还未开始
                voteStatus = -1;
            }
            else if (access.GetUserAction(userId, actionId) > 0)
            {
                //是否已经投票
                voteStatus = 2;
            }
            else
            {
                // 投票过期
                var endTime = actionInfo.EndTime;
                if (endTime != DateTime.MinValue && endTime < DateTime.Now)
                {
                    voteStatus = 3;
                }
            }

            return new Tuple<int, ActionEntity>(voteStatus, actionInfo);
        }

        /// <summary>
        /// 获取用户投票状态
        /// </summary>
        /// <param name="actionId">活动id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public bool IsVoted(int actionId, string userId)
        {
            //默认进行中
            UserActionAccess access = new UserActionAccess();

            //是否已经投票
            int count = access.GetUserAction(userId, actionId);

            return (count > 0);
        }

        /// <summary>
        /// 保存投票结果
        /// </summary>
        /// <param name="actionId"></param>
        /// <param name="userId"></param>
        /// <param name="selectedVoteItem"></param>
        /// <returns></returns>
        public int SaveVotingResult(int actionId, string userId, List<int> selectedVoteItem)
        {
            return new UserActionAccess().SaveVotingResult(actionId, userId, selectedVoteItem) ? 0 : 1;
        }
    }
}
